﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Utilities
{
    public class ReadPassword
    {
        /// <param name="prompt">String to be outputed before reading.</param>
        /// <param name="hide">Should the input be hidden.</param>
        public static string GetConsoleInput(string prompt, bool hide)
        {

            StringBuilder input = new StringBuilder();
            if (prompt != null)
            {
                Console.Write(prompt);
            }
            for (ConsoleKeyInfo keyinfo = Console.ReadKey(true); keyinfo.Key != ConsoleKey.Enter; keyinfo = Console.ReadKey(true))
            {
                //handle backspace
                if (keyinfo.Key == ConsoleKey.Backspace)
                {
                    if (input.Length > 0)
                    {
                        Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
                        Console.Write(" ");
                        Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
                        input.Length -= 1;
                    }
                }
                else
                {
                    Console.Write(hide ? '*' : keyinfo.KeyChar);
                    input.Append(keyinfo.KeyChar);
                }
            }
            Console.WriteLine();

            return input.ToString();

        }
    }
}
